package com.parktech.sun.utils;

import org.apache.html.dom.HTMLDocumentImpl;
import org.cyberneko.html.parsers.DOMFragmentParser;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.StringReader;

/**
 * User: Think
 * Date: 11-1-22
 * Time: 上午10:40
 */
public class HTMLHelper {

    public static String getContentText(String content) throws IOException, SAXException {
        DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
        DOMFragmentParser parser = new DOMFragmentParser();
        parser.parse(new InputSource(new StringReader(content)), node);
        StringBuffer sb = new StringBuffer();
        getText(sb, node);
        return sb.toString();
    }

    private static void getText(StringBuffer sb, Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            sb.append(node.getNodeValue());//取得结点值，即开始与结束标签之间的信息
        }
        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                getText(sb, children.item(i));//递归遍历DOM树
            }
        }
    }

}
